<template>
  <div class="software-download-center">
    <!-- 顶部英雄区域 -->
    <section class="hero-section">
      <div class="hero-content">
        <h1 class="hero-title">探索优质软件资源</h1>
        <p class="hero-subtitle">安全、可靠、高速下载体验</p>
        
        <!-- 搜索框 -->
        <div class="search-container">
          <el-input
            v-model="searchQuery"
            placeholder="搜索软件..."
            class="search-input"
            size="large"
            @keyup.enter="searchSoftware"
          >
            <template #prefix>
              <el-icon class="search-icon"><Search /></el-icon>
            </template>
            <template #append>
              <el-button 
                type="primary" 
                @click="searchSoftware"
                :loading="loading"
                class="search-button"
              >
                搜索
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
    </section>

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 筛选工具栏 -->
      <div class="filter-toolbar">
        <div class="filter-group">
          <el-select
            v-model="selectedCategory"
            placeholder="所有分类"
            class="category-select"
            size="large"
            @change="filterSoftware"
          >
            <el-option
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            >
              <div class="category-option">
                <el-icon :size="18" :color="category.color">
                  <component :is="category.icon" />
                </el-icon>
                <span>{{ category.label }}</span>
              </div>
            </el-option>
          </el-select>
        </div>

        <div class="sort-group">
          <el-radio-group v-model="sortMethod" size="large" @change="sortSoftware">
            <el-radio-button label="popular">
              <el-icon><Star /></el-icon>
              热门
            </el-radio-button>
            <el-radio-button label="download">
              <el-icon><Download /></el-icon>
              下载量
            </el-radio-button>
            <el-radio-button label="update">
              <el-icon><Clock /></el-icon>
              最新
            </el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 软件列表 -->
      <div class="software-list">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <el-skeleton :count="6" animated>
            <template #template>
              <el-skeleton-item variant="image" style="width: 100%; height: 180px; border-radius: 8px;" />
              <div style="padding: 14px;">
                <el-skeleton-item variant="h3" style="width: 80%; margin-bottom: 10px;" />
                <el-skeleton-item variant="text" style="width: 60%;" />
                <div style="display: flex; margin-top: 16px;">
                  <el-skeleton-item variant="button" style="width: 50%; margin-right: 8px;" />
                  <el-skeleton-item variant="button" style="width: 50%;" />
                </div>
              </div>
            </template>
          </el-skeleton>
        </div>

        <!-- 空状态 -->
        <el-empty 
          v-else-if="softwareList.length === 0" 
          description="没有找到符合条件的软件"
          class="empty-state"
        >
          <el-button type="primary" @click="resetFilters">重置筛选条件</el-button>
        </el-empty>

        <!-- 软件卡片列表 -->
        <div v-else class="software-grid">
          <div 
            v-for="software in softwareList" 
            :key="software.id" 
            class="software-card"
            @click="navigateToDetail(software.id)"
          >
            <div class="software-badge" v-if="software.isNew">
              <span>NEW</span>
            </div>
            <div class="software-image">
              <el-image
                :src="software.cover_image || placeholderImage"
                :alt="software.name"
                fit="cover"
                loading="lazy"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="software-content">
              <div class="software-header">
                <h3 class="software-title">{{ software.name }}</h3>
                <el-tag 
                  :type="getCategoryType(software.category)" 
                  size="small"
                  class="software-category"
                >
                  {{ software.category }}
                </el-tag>
              </div>
              <p class="software-description">{{ software.description }}</p>
              <div class="software-meta">
                <div class="meta-item">
                  <el-icon><Download /></el-icon>
                  <span>{{ formatNumber(software.download_count) }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatRelativeTime(software.updated_at) }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Files /></el-icon>
                  <span>{{ software.version }}</span>
                </div>
              </div>
              <div class="software-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click.stop="downloadSoftware(software.file_path)"
                  class="download-button"
                >
                  <el-icon><Download /></el-icon>
                  下载
                </el-button>
                <el-button 
                  type="default" 
                  size="small" 
                  @click.stop="navigateToDetail(software.id)"
                  class="detail-button"
                >
                  <el-icon><InfoFilled /></el-icon>
                  详情
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页控件 -->
        <div class="pagination-container" v-if="softwareList.length > 12">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalItems"
            :page-sizes="[12, 24, 36, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            background
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { getAllSoftware } from '@/api/software'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Search, Download, Clock, Star, Picture, 
  InfoFilled, OfficeBuilding, Brush, 
  Cpu, Lock, VideoPlay, More 
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import placeholderImage from '@/assets/default-software.png'

const router = useRouter()

// 数据状态
const softwareList = ref([])
const searchQuery = ref('')
const selectedCategory = ref('')
const sortMethod = ref('popular')
const loading = ref(true)
const currentPage = ref(1)
const pageSize = ref(12)
const totalItems = ref(0)

// 分类选项
const categories = ref([
  { value: '', label: '全部', icon: More, color: '#909399' },
  { value: 'office', label: '办公软件', icon: OfficeBuilding, color: '#409EFF' },
  { value: 'design', label: '设计软件', icon: Brush, color: '#67C23A' },
  { value: 'development', label: '开发工具', icon: Cpu, color: '#E6A23C' },
  { value: 'security', label: '安全软件', icon: Lock, color: '#F56C6C' },
  { value: 'entertainment', label: '娱乐软件', icon: VideoPlay, color: '#909399' }
])

// 模拟获取软件数据
const fetchSoftwareList = async () => {
  try {
    loading.value = true
    let mockData = await getAllSoftware()
    
    // 应用筛选条件
    let filteredData = [...mockData]
    
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      filteredData = filteredData.filter(item => 
        item.name.toLowerCase().includes(query) || 
        item.description.toLowerCase().includes(query))
    }
    
    if (selectedCategory.value) {
      filteredData = filteredData.filter(item => item.category === selectedCategory.value)
    }
    
    // 应用排序
    switch (sortMethod.value) {
      case 'download':
        filteredData.sort((a, b) => b.download_count - a.download_count)
        break
      case 'update':
        filteredData.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
        break
      default:
        // 热门排序（综合下载量和更新时间）
        filteredData.sort((a, b) => 
          (b.download_count * 0.7 + new Date(b.updated_at).getTime() * 0.3) - 
          (a.download_count * 0.7 + new Date(a.updated_at).getTime() * 0.3)
        )
    }
    
    totalItems.value = filteredData.length
    softwareList.value = filteredData.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
    )
  } catch (error) {
    ElMessage.error('获取软件列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 搜索软件
const searchSoftware = () => {
  currentPage.value = 1
  fetchSoftwareList()
}

// 筛选软件
const filterSoftware = () => {
  currentPage.value = 1
  fetchSoftwareList()
}

// 排序软件
const sortSoftware = () => {
  fetchSoftwareList()
}

// 重置筛选条件
const resetFilters = () => {
  searchQuery.value = ''
  selectedCategory.value = ''
  sortMethod.value = 'popular'
  currentPage.value = 1
  fetchSoftwareList()
}

// 分页变化处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchSoftwareList()
}

const handlePageChange = (newPage) => {
  currentPage.value = newPage
  fetchSoftwareList()
}

// 导航到详情页
const navigateToDetail = (id) => {
  router.push(`/software/${id}`)
}

// 下载软件
const downloadSoftware = (file_path) => {
  ElMessage.success(`开始下载软件`)
  window.open(`${file_path}`, '_blank')
}

// 获取分类标签类型
const getCategoryType = (category) => {
  const typeMap = {
    'office': 'primary',
    'design': 'success',
    'development': 'warning',
    'security': 'danger',
    'entertainment': 'info',
    'other': 'default'
  }
  return typeMap[category] || 'default'
}

// 格式化数字
const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toString()
}

// 格式化相对时间
const formatRelativeTime = (dateString) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffInDays = Math.floor((now - date) / (1000 * 60 * 60 * 24))
  
  if (diffInDays === 0) return '今天'
  if (diffInDays === 1) return '昨天'
  if (diffInDays < 7) return `${diffInDays}天前`
  if (diffInDays < 30) return `${Math.floor(diffInDays / 7)}周前`
  return `${Math.floor(diffInDays / 30)}月前`
}

// 初始化加载数据
onMounted(() => {
  fetchSoftwareList()
})
</script>
<style scoped>
.software-download-center {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  color: #333;
  background-color: #f8fafc;
}

/* Hero Section */
.hero-section {
  position: relative;
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: white;
  padding: 4rem 1rem 6rem;
  text-align: center;
  overflow: hidden;
}

.hero-content {
  max-width: 1200px;
  margin: 0 auto;
  position: relative;
  z-index: 2;
}

.hero-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
  line-height: 1.2;
}

.hero-subtitle {
  font-size: 1.25rem;
  opacity: 0.9;
  margin-bottom: 2rem;
}

.search-container {
  max-width: 700px;
  margin: 0 auto;
}

.search-input {
  border-radius: 50px;
  overflow: hidden;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 50px 0 0 50px !important;
  box-shadow: none !important;
}

.search-input :deep(.el-input-group__append) {
  border-radius: 0 50px 50px 0 !important;
  box-shadow: none !important;
  padding: 0 1.5rem;
}

.search-button {
  font-weight: 500;
}

.search-icon {
  color: #94a3b8;
  margin-right: 0.5rem;
}

.hero-wave {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100px;
}

.hero-wave svg {
  width: 100%;
  height: 100%;
  display: block;
}

/* Main Content */
.main-content {
  max-width: 1200px;
  margin: -2rem auto 3rem;
  padding: 0 1rem;
  position: relative;
}

/* Filter Toolbar */
.filter-toolbar {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1.5rem;
  background: white;
  padding: 1rem;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.filter-group, .sort-group {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.category-select {
  width: 200px;
}

.category-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* Software List */
.software-list {
  margin-top: 1.5rem;
}

.loading-state {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.empty-state {
  background: white;
  padding: 3rem 1rem;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* Software Grid */
.software-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1.5rem;
}

.software-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
}

.software-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}

.software-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #f43f5e;
  color: white;
  font-size: 0.75rem;
  font-weight: bold;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  z-index: 2;
}

.software-image {
  height: 160px;
  width: 100%;
  overflow: hidden;
  position: relative;
}

.software-image :deep(.el-image) {
  width: 100%;
  height: 100%;
  display: block;
}

.software-image :deep(.el-image__inner) {
  transition: transform 0.3s ease;
}

.software-card:hover :deep(.el-image__inner) {
  transform: scale(1.05);
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f1f5f9;
  color: #94a3b8;
}

.image-error .el-icon {
  font-size: 2.5rem;
}

.software-content {
  padding: 1.25rem;
}

.software-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.75rem;
}

.software-title {
  font-size: 1.125rem;
  font-weight: 600;
  margin: 0;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.software-category {
  margin-left: 0.5rem;
  flex-shrink: 0;
}

.software-description {
  color: #64748b;
  font-size: 0.875rem;
  line-height: 1.5;
  margin-bottom: 1rem;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.software-meta {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
  font-size: 0.75rem;
  color: #64748b;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.meta-item .el-icon {
  font-size: 0.875rem;
}

.software-actions {
  display: flex;
  gap: 0.5rem;
}

.download-button {
  flex: 1;
}

.detail-button {
  flex: 1;
}

/* Pagination */
.pagination-container {
  margin-top: 2rem;
  display: flex;
  justify-content: center;
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* Responsive Adjustments */
@media (max-width: 768px) {
  .hero-title {
    font-size: 2rem;
  }
  
  .hero-subtitle {
    font-size: 1rem;
  }
  
  .filter-toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .category-select {
    width: 100%;
  }
  
  .sort-group {
    justify-content: center;
  }
  
  .software-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
}

@media (max-width: 480px) {
  .hero-title {
    font-size: 1.75rem;
  }
  
  .software-grid {
    grid-template-columns: 1fr;
  }
  
  .software-actions {
    flex-direction: column;
  }
  
  .download-button, .detail-button {
    width: 100%;
  }
}
</style>